 	; This is just a trick to create constants
	.ORIG 2048
ASize:	; Size of the array is 512 elements (2048 bytes) 
	.ORIG 1000
ItNum:	;  Number of sorting iterations
	
	.ORIG 8192
Stack:	; Stack begins at the very top of memory

	;  Now the actual code
	.ORIG 0x400
	XOR	S0,S0,S0	; Not using GP, we use S0 to hold value zero
	ADDI	SP,S0,Stack	; Put SP at top of our memory

	; Initialize the array
	ADDI	T0,S0,Array	; T0 = Address of array
	ADDI	T1,S0,ASize
	ADD	T1,T0,T1	; T1 = End of array
	ADDI	T2,S0,1000	; T2 is 1000 
	SUBI	T0,T0,-4	; Array[0] already initialized
Init:
	SW	T2,0(T0)
	ADDI	T2,T2,7
	ADDI	T0,T0,4
	SUB	T3,T0,T1
	LTI	T3,T3,0
	BNEZ	T3,Init

	ADDI	T0,S0,ItNum	; Iteration count kept in T0
Loop:
	SUBI	SP,SP,4
	SW	T0,0(SP)	; Save loop counter to stack
	ADDI	A0,S0,Array	; A0 - Address of array
	ADDI	A1,A0,ASize	; A1 - End of array
	ADDI	A2,S0,0		; Sort in ascending order
	JRL	RA,Sort(S0)	; Call Sort
	BEQZ	RV,Error
	ADDI	A0,S0,Array	; A0 - Address of array
	ADDI	A1,A0,ASize	; A1 - End of array
	ADDI	A2,S0,1		; Sort in descending order
	ADDI	T0,S0,Sort
	JRL	RA,0(T0)	; Call Sort
	BEQZ	RV,Error
	LW	T0,0(SP)	; Restore loop counter from stack 
	ADDI	SP,SP,4
	SUBI	T0,T0,1
	SW	T0,0xF800(S0)	; Send counter to HEX display
	BNEZ	T0,Loop

	ADDI	T0,S0,Array	; T0 = Address of array
	ADDI	T1,T0,ASize	; T1 = End of array
	ADDI	T2,S0,1000	; T2 is 1000
	LW	A0,0(T0)
	ADDI	A1,S0,Stack
	BNE	A0,A1,Error
	ADDI	T0,T0,4
Check:
	BEQ	T1,T0,Done
	SUBI	T1,T1,4
	LW	A0,0(T1)
	BNE	A0,T2,Error
	ADDI	T2,T2,7
	BEQ	T2,T2,Check
Done:
	ADDI	T0,S0,0xFFFF	; Display FFFF
	SW	T0,0xF800(S0)
	BNEZ	T0,Done		; Loops forever

Error:
	ADDI	T0,S0,0xEEEE	; Display EEEE
	SW	T0,0xF800(S0)
	BNEZ	T0,Error	; Loops forever
	
Sort:	; Sort(beg,end,order)
	; Sorts an array that starts at beg and ends at end
	; If order==0, sorts in ascending order (low to high)
	; If order==1, sorts in descending order (high to low)
	ADDI	T0,A0,0
LoopI:
	BEQ	T0,A1,EndI
	ADDI	T1,T0,4
LoopJ:	
	BEQ	T1,A1,EndJ
	LW	T2,0(T0)
	LW	T3,0(T1)
	BNEZ	A2,Descend
	LT	RV,T2,T3
	BEQ	RV,RV,Decide
Descend:
	LT	RV,T3,T2
Decide:
	BNEZ	RV,NoSwap
Swap:
	SW	T2,0(T1)
	SW	T3,0(T0)
NoSwap:		
	ADDI	T1,T1,4
	BEQ	T1,T1,LoopJ
EndJ:	
	ADDI	T0,T0,4
	BEQ	T0,T0,LoopI
EndI:
	ADDI	RV,RV,1
	JRL	T0,0(RA)
	
Array:
	.WORD Stack
